<template>
  <div id="navigation" v-show="show">
    <div class="top">
      <!-- 交通工具 -->
      <div class="icon-btns">
        <div class="traffic-btns">
          <button>
            <i class="iconfont icon-qiche car"></i>
          </button>
          <button>
            <i class="iconfont icon-gongjiaoche bus"></i>
          </button>
          <button>
            <i class="iconfont icon-buxing walk"></i>
          </button>
        </div>
        <div class="chaohao-btn">
          <button @click="handleClose">
            <i class="iconfont icon-chahao"></i>
          </button>
        </div>
      </div>
      <!-- 输入框 -->
      <div class="inputs">
        <el-input
          v-model="inputStart"
          type="text"
          placeholder="请输入起点"
          clearable
          @input="handleSearchInputPOIstart"
          @focus="activeInput = 'start'"
        />
        <el-input
          v-model="inputEnd"
          type="text"
          placeholder="请输入终点"
          clearable
          @input="handleSearchInputPOIend"
          @focus="activeInput = 'end'"
        />
      </div>
      <!-- 按钮组 -->
      <div class="bottom-btns">
        <button class="clear-btn" @click="handelClear">清楚路线</button>
        <button class="ok-btn" @click="handleOk">开始导航</button>
      </div>
    </div>
    <!-- 导航记录面板 -->
    <div id="history-panel" v-show="showHistory">
      <div class="title">
        <i class="iconfont icon-lishijilu"></i>
        <span>导航记录</span>
      </div>
      <ul v-if="navgationHistory.length > 0">
        <li v-for="(item, index) in navgationHistory" :key="index">
          <i class="iconfont icon-sousuo"></i>
          <span @click="selectHistory(item)">
            {{ item.start }} → {{ item.end }}</span
          >
          <i class="iconfont icon-chahao" @click="removeHistory(index)"></i>
        </li>
      </ul>
      <div v-else class="no-history">暂无搜索记录</div>
      <button
        class="clear-history"
        @click="clearHistory"
        v-if="navgationHistory.length > 0"
      >
        清空历史记录
      </button>
    </div>
    <!-- poi提示面板 -->
    <div id="outinput" v-show="showPoi">
      <ul>
        <li
          v-for="(item, index) in poiInfo"
          :key="index"
          @click="handleSelectPoi(item)"
        >
          <i class="iconfont icon-position"></i>
          <span
            v-html="highlightText(item.name, inputStart)"
            v-if="showHighlight"
          ></span>
          <span v-html="highlightText(item.name, inputEnd)" v-else></span>
          <span>{{ item.address }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, watchEffect, onMounted, onUnmounted } from 'vue';
// 高德地图API加载
import AMapLoader from '@amap/amap-jsapi-loader';

// 注入地图实例
const { exmap } = inject('ex');

// 接收父组件传递的显示状态
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});
// 定义事件，用于通知父组件更新状态
const emit = defineEmits(['update:show']);

// 实时输入内容
const inputStart = ref('');
const inputEnd = ref('');

// 控制poi提示面板显示隐藏
const showPoi = ref(false);
// 存储poi提示信息
const poiInfo = ref([]);

// 高亮切换id
const showHighlight = ref(null);
// 判断哪个输入框聚焦
const activeInput = ref(null);

// 存储导航记录
const navgationHistory = ref([]);
// 控制记录显示隐藏id
const showHistory = ref(true);

// 全局声明
let driving;
let autoComplete;

onMounted(async () => {
  //✅获取历史记录 本地存储
  const savedHistory = localStorage.getItem('navgationHistory');
  if (savedHistory) {
    navgationHistory.value = JSON.parse(savedHistory);
  }

  // ==============🌸高德地图API加载与实例化===============
  // 加载器
  window._AMapSecurityConfig = {
    securityJsCode: '3803fef5273a37c33f6c81666572c9c4',
  };
  // 异步加载高德地图API（等待API加载完成后，在创建底图实例map）
  const AMap = await AMapLoader.load({
    key: '73e59768fece08c22145999d58cdbb7d',
    version: '2.0',
    //引入的插件列表（与api加载器一同加载⚠️）
    plugins: ['AMap.Driving', 'AMap.AutoComplete'],
  });

  // 创建 搜索提示实例
  autoComplete = new AMap.AutoComplete({
    city: '武汉',
    type: 'poi', // 返回结果类型，poi表示兴趣点
  });

  //自动动态监听地图实例
  watchEffect(() => {
    // 创建导航实例
    driving = new AMap.Driving({
      policy: 0,
      map: exmap.value,
    });
  });
});

// ========================🌸功能函数==================
// ✅关闭导航面板，通知父组件更新状态
const handleClose = () => {
  emit('update:show', false);
  // 清除导航路线
  driving.clear();
  inputStart.value = '';
  inputEnd.value = '';
  // 将历史面板id恢复为true
  showHistory.value = true;
};

// ✅高亮显示提示 函数
const highlightText = (text, keyword) => {
  if (!keyword.trim()) return text;
  // 正则全局匹配，不区分大小写
  const regex = new RegExp(`(${keyword})`, 'gi');
  // 替换匹配内容为带highlight类的span
  return text.replace(regex, '<span class="highlight">$1</span>');
};

//✅存储 导航记录
const addToHistory = (start, end) => {
  const content = {
    start: start,
    end: end,
  };
  // 去重处理：如果已存在则移到最前面
  const index = navgationHistory.value.findIndex(
    (item) => item.start === content.start && item.end === content.end
  );
  if (index !== -1) {
    navgationHistory.value.splice(index, 1);
    console.log('移动到最前面');
  }
  // 将搜索内容添加到记录数组的开头
  navgationHistory.value.unshift(content);
  // 限制历史记录数量为8条
  if (navgationHistory.value.length > 8) {
    // 移除数组的最后一个元素
    navgationHistory.value.pop();
  }
  // ➕保存到本地存储
  localStorage.setItem(
    'navgationHistory',
    JSON.stringify(navgationHistory.value)
  );
};

// ===========================🌸提示面板=====================
//👀起点提示
const handleSearchInputPOIstart = () => {
  // 0️⃣输入时，隐藏历史面板
  showHistory.value = false;

  // 0️⃣不同输入框，展示不同的提示高亮
  showHighlight.value = true;

  // 1️⃣有输入内容则显示联想面板，无内容则隐藏
  const valstart = inputStart.value.trim();
  showPoi.value = valstart !== '';
  if (!valstart) {
    poiInfo.value = [];
    return;
  }
  //2️⃣调用 autoComplete.search 接口-》获取输入提示结果，并存储
  autoComplete.search(valstart, (status, result) => {
    if (status === 'complete' && result && result.tips) {
      /*    console.log('AutoComplete 搜索结果:', result.tips); */
      // 将联想结果存入自定义数组
      poiInfo.value = result.tips.map((tip) => ({
        name: tip.name,
        address: tip.district,
      }));
    } else {
      poiInfo.value = [];
      console.log('AutoComplete 搜索无结果或失败');
    }
  });
};
// 👀终点提示
const handleSearchInputPOIend = () => {
  // 0️⃣输入时，隐藏历史面板
  showHistory.value = false;

  // 0️⃣不同输入框，展示不同的提示高亮
  showHighlight.value = false;

  // 1️⃣有输入内容则显示联想面板，无内容则隐藏
  const valend = inputEnd.value.trim();
  showPoi.value = valend !== '';
  if (!valend) {
    poiInfo.value = [];
    return;
  }
  //2️⃣调用 autoComplete.search 接口-》获取输入提示结果，并存储
  autoComplete.search(valend, (status, result) => {
    if (status === 'complete' && result && result.tips) {
      /*  console.log('AutoComplete 搜索结果:', result.tips); */
      // 将联想结果存入自定义数组
      poiInfo.value = result.tips.map((tip) => ({
        name: tip.name,
        address: tip.district,
      }));
    } else {
      poiInfo.value = [];
      console.log('AutoComplete 搜索无结果或失败');
    }
  });
};

// 👀提示面板 选中项
const handleSelectPoi = (item) => {
  // 监听不同输入框，填充到输入框
  if (activeInput.value === 'start') {
    inputStart.value = item.name;
  } else if (activeInput.value === 'end') {
    inputEnd.value = item.name;
  }
  // 隐藏提示信息面板
  showPoi.value = false;
};

// ===========================🌸导航记录=====================
// 2️⃣选择历史记录项->填加到输入框
const selectHistory = (item) => {
  // 填充到输入框
  const { start, end } = item;
  inputStart.value = start;
  inputEnd.value = end;
  // 开启导航
  navigationGO();
};

// 3️⃣清空历史记录
const clearHistory = () => {
  navgationHistory.value = [];
  localStorage.removeItem('navgationHistory'); // 同时清除本地存储
};

// 4️⃣删除选中的历史记录
const removeHistory = (index) => {
  navgationHistory.value.splice(index, 1);
  localStorage.setItem(
    'navgationHistory',
    JSON.stringify(navgationHistory.value)
  );
};

// ===========================🌸导航功能=====================
// ⚠️封装 导航功能 + 保存记录
const navigationGO = () => {
  // 0️⃣每次导航前清除之前的路线
  if (driving) {
    driving.clear();
  }

  // 1️⃣导航功能
  // 1. 空值校验：防止未输入起点/终点导致报错
  if (!inputStart.value.trim() || !inputEnd.value.trim()) {
    alert('请完整输入起点和终点');
    return;
  }
  // 2. 动态构建路径点：每次点击时获取最新输入值
  const points = [
    { keyword: inputStart.value, city: '全国' },
    { keyword: inputEnd.value, city: '全国' },
  ];
  // 3. 将路径绘制在地图上
  driving.search(points);

  // 2️⃣保存导航记录
  addToHistory(inputStart.value, inputEnd.value);
  console.log('保存导航记录成功', navgationHistory.value);
};

// 👀开始导航
const handleOk = () => {
  navigationGO();
};

// ==============🌸清除路线=========
const handelClear = () => {
  //清楚路线
  driving.clear();
  inputStart.value = '';
  inputEnd.value = '';
  // 显示历史面板
  showHistory.value = true;
};
</script>

<style lang="scss" scoped>
@import '//at.alicdn.com/t/c/font_4989585_1or9e18iesl.css';
#navigation {
  position: absolute;
  top: 0px;
  left: 0px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  .top {
    width: 350px;
    background-color: #3d93fd;
    .icon-btns {
      display: flex;
      .traffic-btns {
        display: flex;
        padding: 14px 0;
        padding-left: 96px;
        gap: 45px;
        flex: 4;
      }
      .chaohao-btn {
        display: flex;
        justify-content: center;
        flex: 1;
      }

      button {
        border: none;
        background: none;
        .iconfont {
          color: white;
        }
        .car,
        .walk {
          font-size: 23px;
        }
        .bus {
          font-size: 19px;
        }
      }
    }
    .inputs {
      padding: 0 35px;
      display: flex;
      flex-direction: column;
      gap: 13px;
      .el-input {
        width: 266px;
        height: 26px;
      }
    }
    .bottom-btns {
      display: flex;
      justify-content: space-around;
      gap: 30px;
      padding: 18px 0;
      .clear-btn {
        border: none;
        background: none;
        color: white;
      }
      .ok-btn {
        border: none;
        background-color: #559ffb;
        color: white;
        border-radius: 3px;
        padding: 5px 10px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
      }
    }
  }
  #history-panel {
    width: 350px;
    background-color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
    .title {
      width: 90%;
      display: flex;
      gap: 3px;
      margin-top: 12px;
      span {
        font-size: 15px;
        flex: 1;
      }
      i {
        font-size: 14px;
        width: 20px;
        padding-top: 5px;
      }
    }
    ul {
      width: 90%;
      display: flex;
      flex-direction: column;
      margin: 8px 0;
      gap: 5px;
      li {
        margin: 2px 0;
        color: #9b9faf;
        display: flex;
        span {
          font-size: 13px;
          flex: 1;
        }
        i {
          font-size: 12px;
          width: 20px;
          padding-top: 5px;
        }
      }
    }
    .clear-history {
      border-bottom: none;
      border-left: none;
      border-right: none;
      border-top: 1px solid #9b9faf;
      background: none;
      color: #2c9eff;
      font-size: 15px;
      padding: 7px 0;
      width: 100%;
    }
    .no-history {
      color: #9b9faf;
      margin: 6px 0;
    }
  }
  #outinput {
    background-color: white;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
    width: 350px;
    border-radius: 3px;
    ul {
      display: flex;
      flex-direction: column;
      gap: 9px;
      padding: 9px 9px;
      li {
        display: flex;
        align-items: center;
        gap: 6px;
        .icon-position {
          color: #9b9faf;
          font-size: 17px;
        }
        span:nth-child(2) {
          font-size: 14px;
        }
        span:nth-child(3) {
          color: #9b9faf;
          font-size: 12px;
        }
      }
    }
  }
}

// 高亮显示
::v-deep(.highlight) {
  color: #2c9eff;
}
</style>
